import { RouteRecordRaw } from "vue-router";
import { env } from "@/utils/helper.ts";
/*
 * @Author: TJN tjn@246@126.com
 * @Date: 2024-07-15 15:16:42
 * @LastEditors: TJN tjn@246@126.com
 * @LastEditTime: 2024-07-26 16:13:18
 * @FilePath: \router\src\router\autoload.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */

// 读取layouts下面所有的.vue文件
const layouts = import.meta.glob("../../layouts/*.vue", { eager: true });

// 读取views所有子目录下面的所有.vue文件
const views = import.meta.glob("../../views/**/*.vue", { eager: true });

// 遍历父级路由
function getRoutes() {
  const layoutRoutes = [] as RouteRecordRaw[];

  Object.entries(layouts).forEach(([file, module]) => {
    const route = getRouteByModule(file, module);

    route.children = getChildrenRoutes(route);

    layoutRoutes.push(route);
  });

  return layoutRoutes;
}

// 遍历子级路由
function getChildrenRoutes(route: RouteRecordRaw) {
  const routes = [] as RouteRecordRaw[];
  Object.entries(views).forEach(([file, module]) => {
    if (file.includes(`../views/${route.name as string}`)) {
      const route = getRouteByModule(file, module);

      routes.push(route);
    }
  });
  return routes;
}

// 处理路由的方法
function getRouteByModule(file: string, module: any) {
  // const name = file.split("/").pop()?.split(".")[0];

  const name = file.replace(/.+layouts\/|.+views\/|\.vue/gi, "");
  console.log(name,'name')
     const route = {
    path: `/${name}`,
    name: name.replace("/", "-"),
    component: module.default,
  } as RouteRecordRaw;
console.log(route,'route')
  return Object.assign(route, module.default?.route);
}



// const routes = env.VITE_ROUTER_AUTOLOAD
//   ? getRoutes()
//   : ([] as RouteRecordRaw[]);
export default getRoutes;
